//
//  MonitorListViewController.m
//  OGL
//
//  Created by ZengYuan on 15/1/5.
//  Copyright (c) 2015年 ZengYuan. All rights reserved.
//

#import "MonitorListViewController.h"
#import "ChannelListCell.h"
#import "MonitorViewController.h"
//#import "BabyInfo.h"
//#import "WeekScheduleCell.h"
//#import "WeekUnit.h"
//#import "GPUImage.h"
#import "AppDelegate.h"
#import "UserUnit.h"
#import "UserLogin.h"
#import "DeviceUnit.h"
#import "FindRouteListViewController.h"
#import "DeviceHandle.h"
#import "InputTextViewController.h"

//#import "BabyManager.h"

BOOL  g_allowUserPlayVideoIn3G = NO;

@interface MonitorListViewController ()
{
    float monitorPreViewHeight ;
    
    NSDate *serverCurrentDate;  //服务器后台当前时间
    NSInteger weekCurrentDay;  // 服务器星期几
    
    BOOL currentSystemTimeModified;
    
//    WeekUnit*currentWeekUnit;
    
    CGPoint initialPoint;
    CGFloat initialBoardSideViewX;
    
    BOOL weekRulesLoading;
    
    NSTimeInterval server_localTimeIntervel;
    
//    KinderInfo *currentKindInfo;
}
@end

@implementation MonitorListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    system_local_timeInterval=nil;
    
    CGRect rect = self.tableView.frame;
    rect.size.height = self.view.frame.size.height - self.navigationController.navigationBar.frame.size.height - (OSVersionIsAtLeastiOS7?20:0);
    self.tableView.frame=rect;

    monitorPreViewHeight = 236;
//    
//    BabyInfo *babyInfo = [[BabyManager shareInstance] currentBabyInfo];
//    currentKindInfo = babyInfo.curSelectedKinder;
    
    [self addFullloadView];
    [fullloadingView showLoadingState];
    [fullloadingView.btn addTarget:self action:@selector(getData) forControlEvents:UIControlEventTouchUpInside];
    
    
    captureImgDic=[[NSMutableDictionary alloc]init];
    g_allowUserPlayVideoIn3G=NO;
    
    if (self.device_unit.device_id) {
        [self getData];
    }
    
//    [self.rightBtnPar setTitle:@"搜索" forState:UIControlStateNormal];
//    self.titleLabel.text=@"智能设备";

    self.titleLabel.text=@"我的设备";
    
    
    //管理员，获取时间规则
    
    __weak typeof(self) weakSelf = self;
    [DeviceHandle deviceGetTimeInterval:self.device_unit.device_id success:^(NSString *_start_time, NSString *_end_time) {
        start_time = _start_time;
        end_time   = _end_time;
        [weakSelf.tableView reloadData];
    } failure:^(NSString *error) {
        
    }];

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.tableView reloadData];
}

//
//-(void)navRightAction{
//    //
//    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    FindRouteListViewController *frlv = [board instantiateViewControllerWithIdentifier:@"findrvc"];
//    frlv.hidesBottomBarWhenPushed=YES;
//    
//    frlv.router_id = self.router_id;
//    [self.navigationController pushViewController:frlv animated:YES];
//    
//}


-(void)getData{
    
    Reachability*rea= [Reachability reachabilityForInternetConnection];
    if ([rea isReachable]) {
        //网络通，可以获取
        
        [self requestIPCS];
    }else{
        if (fullloadingView) {
            [fullloadingView showErrorMsg:HTTPERROR_CANNOTREACH];
        }else{
            MBALERT(HTTPERROR_CANNOTREACH);
        }
        
        [self doneLoadingTableViewData];
    }
    
}

-(void)requestIPCS{
    
    NSString *url = [NSString stringWithFormat:MAINURL, URL_GETDEVICE_CHANNELS];
    __unsafe_unretained typeof(self) weakSelf = self;
    
    
    NSString *sid = [[NSUserDefaults standardUserDefaults] objectForKey:@"session_id"];
    
    if(!sid)return;
    
    NSDictionary *dic = [[NSDictionary alloc] initWithObjects: @[sid,self.device_unit.device_id] forKeys:@[@"session_id",@"device_id"]];
    NSString *json  =[dic JSONString];
    
    __weak typeof(self) weakself = self;

    [AWHttpTool post:url body:json success:^(id json) {
        if (json) {
            [self doneLoadingTableViewData];
            NSInteger sta = [json[@"status"] integerValue];
            
            if (sta == 0) {
                
                NSArray *device_channels = json[@"device_channels"];
                
                NSMutableArray *tempArray = [ChannelUnit objectArrayWithKeyValuesArray:device_channels];
                
                if (freshPos== EGORefreshHeader) {
                    self.dataArray = [NSMutableArray array];
                    
                    if(tempArray.count){
                        [weakself dismissFullloadingView];
                    }else{
                        if (fullloadingView) {
                            [fullloadingView showErrorMsg:@"empty device"];
                        }else{
                            MBALERT(@"empty device");
                        }

                    }
                    
                }else{
                    
                }
                
                [self.dataArray addObjectsFromArray:tempArray];
                [weakSelf.tableView reloadData];
                
            }else{
                NSString *err = json[@"msg"];
                [weakself showErrorTipMsgInViewController:err];
            }
        }
    } failure:^(NSError *error) {

        [self doneLoadingTableViewData];
        [weakself showErrorTipMsgInViewController:error.domain];

//        MBALERT(HTTPERROR_DATAFAIL);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//-(void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    self.titleLabel.text=@"爱维课堂秀";
//    
//    [self.tableView reloadData];
//    
//    //    BabyInfo*  babyInfo =[BabyInfo getBabyInfo];
//    //    if(babyInfo){
//    //        [self requestWeekVideoRule:babyInfo.cid];
//    //    }
//}

-(void)setNavbarItem{
    [super setNavbarItem];
    
    [self.rightBtnPar setFrame:CGRectMake(0, 0, 30, 30)];
        [self.rightBtnPar setImage:[UIImage imageNamed:@"icon-本周安排选中"] forState:UIControlStateHighlighted];
    [self.rightBtnPar setImage:[UIImage imageNamed:@"icon-本周安排默认"] forState:UIControlStateNormal];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == self.tableView) {
        return 1;
    }else{
        return 1;
    }
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.tableView) {
        return self.dataArray.count;
    }else{
        if (weekRulesLoading==1) {
            //正在加载
            return 1;
        }else{
            //没有规则
            if (!weekRulesArray.count) {
                return 1;
            }
            //有规则
            return weekRulesArray.count;
        }
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
        return monitorPreViewHeight ;
    }else{
        return 120*VECTOR_IPHONE6;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (tableView == boardSideTableView) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 0)
                        ];
        view.backgroundColor=[UIColor whiteColor];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(33, view.bounds.size.height-18-20, 100, 20)];
        titleLabel.text=@"本周安排";
        titleLabel.font=[UIFont systemFontOfSize:18];
        [view addSubview:titleLabel];
        titleLabel.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        
        HorizonLine *line = [[HorizonLine alloc]initWithFrame:CGRectMake(33, view.bounds.size.height, view.bounds.size.width, 1)];
        [line setLineColor:RGB(221, 221, 221)];
        [view addSubview:line];
        line.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        
        return view;
        
    }else{
        return nil;
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == boardSideTableView) {
        return 78*VECTOR_IPHONE6;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_tableView == self.tableView) {
        __weak typeof(self) weakSelf = self;
        
        static NSString *CellActivity = @"CellActivity";
        ChannelListCell *cell=[_tableView dequeueReusableCellWithIdentifier:CellActivity];
        if (!cell) {
            cell=[[[NSBundle mainBundle] loadNibNamed:@"ChannelListCell" owner:self options:nil] objectAtIndex:0];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor=[UIColor clearColor];
        }

        
         ChannelUnit*channel = self.dataArray[indexPath.row];
         cell.titleLabel.text = channel.device_channel_name;

        UIImage *image =[self captureImage:channel.device_channel_name];
        if (image) {
            NSLog(@"image...");
                cell.previewLogoView.image=image;
                cell.previewLogoView.contentMode =UIViewContentModeScaleAspectFill;
                
            }else{
                cell.previewLogoView.image=[UIImage imageNamed:@"preview_logo"];
                cell.previewLogoView.contentMode =UIViewContentModeCenter;
            }
        
        cell.changeBlock = ^(){
            [weakSelf changeChannelName:indexPath];
        };
        
        
        return cell;
        
    }
 
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
         if (tableView == self.tableView) {
            
            //时间规则判断
            if (![self personRulesAvailble]) {
                MBALERT(@"非开放时间");
                return;
             }
 
            __weak typeof(self) weakself = self;

            
            if(self.device_unit.value == 2){
                [DeviceHandle deviceAvailble:self.device_unit.device_id result:^(BOOL availble) {
                    if (availble) {
                        [weakself pushMon];
                    }
                }];
            }else{
                [self pushMon];
            }
            

        }
        
 }

-(void)changeChannelName:(NSIndexPath *)indexpath{
    
    selIndexPath = indexpath;
    ChannelUnit*channel = self.dataArray[indexpath.row];
    
    InputTextViewController *itvc = [[InputTextViewController alloc]init];
    itvc.originalText = channel.device_channel_name;
    itvc.navTitle = @"通道名";
    itvc.delegate = self;
    [self.navigationController pushViewController:itvc animated:YES];
    
    
}

-(void)DidInputNewText:(NSString *)text{
    
    ChannelUnit*channel = self.dataArray[selIndexPath.row];
    channel.device_channel_name = text;
    [self.tableView reloadData];
    
    [DeviceHandle channelChangeName:text deviceId:self.device_unit.device_id device_channel_no:channel.device_channel_no success:^{
        MBALERT(@"修改成功");
    } failure:^(NSString *error) {
        
    }];

    
}



-(void)pushMon{
    MonitorViewController *truemvc = [[MonitorViewController alloc]init];
    //            truemvc.currentWeekUnit   = currentWeekUnit;
    truemvc.servertinterval=[self localTimeServerTimeInterval];
    truemvc.currentDeviceIndex=0;
    truemvc.beginDate = start_time_date;
    truemvc.endDate = end_time_date;
    truemvc.devicesArray = self.dataArray;
    [self.navigationController pushViewController:truemvc animated:YES];
}

//判断个人时间规则是否可以正常播放
-(BOOL)personRulesAvailble{
    //个人时间规则不成立，可以播放。
    
    if (!start_time || !end_time) {
        return NO;
    }
    
    NSDate *date = [NSDate date];
    
    //当前的年月日
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:localTimeZone];
    [formatter setDateFormat : @"yyyy-MM-dd"];
    NSString *forpart =  [formatter stringFromDate:date];
    
    NSString *startTimeStr = [forpart stringByAppendingFormat:@" %@", start_time];
    NSString *endTimeStr = [forpart stringByAppendingFormat:@" %@", end_time];
    
    start_time_date = [SystemUtils dateByString:startTimeStr];
    end_time_date = [SystemUtils dateByString:endTimeStr];

    return [SystemUtils date:date betweenDate:start_time_date andDate:end_time_date];

    
}

-(NSArray *)capturesArray:(NSArray *)devicesArray{

    NSMutableArray *array = [NSMutableArray array];
    
    for(int i = 0; i<devicesArray.count; i++){
        DeviceUnit *du = [devicesArray objectAtIndex:i];
        UIImage *img = [self captureImage:du.device_channel_name];
        
         if (img) {
            [array addObject:img];
        }else{
            [array addObject:[NSNull null]];
        }
    }
    
    return array;
}

-(void)addBoardSideView{
    CGFloat h = KEY_WINDOW.frame.size.height;
    
    if (!boardSideView) {
        boardSideView = [[UIView alloc]initWithFrame:
                         CGRectMake(KEY_WINDOW.bounds.size.width, 0,
                                    KEY_WINDOW.bounds.size.width,
                                    KEY_WINDOW.bounds.size.height)];
        [KEY_WINDOW addSubview:boardSideView];
        [boardSideView setBackgroundColor:[UIColor clearColor]];
        
        
        
        UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:boardSideView.bounds];
        [boardSideView addSubview:btn];
        [btn setAdjustsImageWhenHighlighted:NO];
        [btn addTarget:self action:@selector(navRightAction) forControlEvents:UIControlEventTouchUpInside];
        btn.tag=100;
        
        boardSideTableView = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-280, 0, 280, h) style:UITableViewStylePlain];
        [boardSideView addSubview:boardSideTableView];
        boardSideTableView.delegate=self;
        boardSideTableView.dataSource=self;
        boardSideTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(boardSideTableView.frame.origin.x-8, 30, 8, 19)];
        [boardSideView addSubview:imgview];
        [imgview setImage:[UIImage imageNamed:@"white_arrow_left"]];
        
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
        [boardSideView addGestureRecognizer:panGesture];
        //        UIImageView *arrowImgView =[[UIImageView alloc]initWithFrame:CGRectMake(70-9, 35, 9, 19)];
        //        [boardSideView addSubview:arrowImgView];
        //        arrowImgView.image=[UIImage imageNamed:@"white_arrow_left"];
        
    }
    
}

-(void)removeBoardSideView{
    if (boardSideTableView) {
        boardSideTableView.delegate=nil;
        boardSideTableView.dataSource=nil;
        [boardSideTableView removeFromSuperview];
        boardSideTableView = nil;
    }

    if (boardSideView) {
        [boardSideView removeFromSuperview];
        boardSideView = nil;
    }
}


-(void)pan:(UIPanGestureRecognizer *)gestureRecognizer{
    static const NSInteger GAUSS_TAG = 0x123;
    __block UIImageView *gaussImgview=(UIImageView *)[KEY_WINDOW viewWithTag:GAUSS_TAG];
    
    
    if(gestureRecognizer.state == UIGestureRecognizerStateBegan){
        initialPoint =  [gestureRecognizer locationInView:self.view];
        initialBoardSideViewX=boardSideView.frame.origin.x;
    }else if(gestureRecognizer.state == UIGestureRecognizerStateChanged){
        CGPoint location = [gestureRecognizer locationInView:self.view];
        
        
        //move boardSideView
        CGRect rect = boardSideView.frame;
        
        if (location.x > initialPoint.x) {
            rect.origin.x = initialBoardSideViewX + (location.x - initialPoint.x);
        }else{
            rect.origin.x = initialBoardSideViewX;
        }
        boardSideView.frame = rect;
        //alpha
        float alpha=1 - rect.origin.x/self.view.frame.size.width;
        alpha = (alpha>1?1:alpha)<0?0:alpha;
        gaussImgview.alpha=alpha;
        
    }else if(gestureRecognizer.state >= UIGestureRecognizerStateEnded){
        CGPoint location = [gestureRecognizer locationInView:self.view];
        
        if (location.x - initialPoint.x>70) {
            
            [UIView animateWithDuration:0.2 animations:^{
                CGRect rect = boardSideView.frame;
                rect.origin.x = self.view.frame.size.width;
                boardSideView.frame=rect;
                
                gaussImgview.alpha=0;
            } completion:^(BOOL finished) {
                [gaussImgview removeFromSuperview];
                gaussImgview = nil;
                
                [self removeBoardSideView];
            }];
            
        }else{
            [UIView animateWithDuration:0.2 animations:^{
                CGRect rect = boardSideView.frame;
                rect.origin.x = 0;
                boardSideView.frame=rect;
                
                gaussImgview.alpha=1;
            } completion:^(BOOL finished) {
            }];
            
        }
        
    }
}

-(UIImage *)gaussImage{
    //make gauss background
//    UIGraphicsBeginImageContextWithOptions(KEY_WINDOW.bounds.size, KEY_WINDOW.opaque, 0.0);
//    [KEY_WINDOW.layer renderInContext:UIGraphicsGetCurrentContext()];
//    UIImage * capture_img = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    
//    GPUImageGaussianBlurFilter * blurFilter = [[GPUImageGaussianBlurFilter alloc] init];
//    blurFilter.blurRadiusInPixels = 5.0;
//    UIImage *blurredImage = [blurFilter imageByFilteringImage:capture_img];
//    return blurredImage;
    
    return nil;
}

-(UIImage *)captureImage:(NSString *)deviceName{
    
    UIImage *image = [captureImgDic objectForKey:deviceName];
    if (image) {
        return image;
    }else{
        NSFileManager*fileManager =[NSFileManager defaultManager];
        NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString*documentsDirectory =[paths objectAtIndex:0];
        
        NSString*imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", deviceName]];
        if ([fileManager fileExistsAtPath:imagePath]) {
            image = [UIImage imageWithContentsOfFile:imagePath];
            [captureImgDic setValue:image forKey:deviceName];
            
            return image;
        }
    }
    
    
    
    
    return nil;
}

- (UIColor *)getColor:(NSString *)hexColor
{
    unsigned int red,green,blue;
    NSRange range;
    range.length = 2;
    
    range.location = 0;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
    
    range.location = 2;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
    
    range.location = 4;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
    
    return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
}

-(UIColor *)weekCircleColor:(NSInteger)row{
    //    NSArray *array=[NSArray arrayWithObjects:[self getColor:@"49cbc9"],
    //                    [self getColor:@"24ae60"],
    //                    [self getColor:@"9acd34"],
    //                    [self getColor:@"ffb957"],
    //                    [self getColor:@"ff5757"], nil];
    NSArray *array = [NSArray arrayWithObjects:RGB(255, 87, 87),RGB(35,175,95),RGB(72,204,200),RGB(255,184,86),RGB(153,204,51), nil];
    return array[row%5];
    
}

-(NSString *)weekName:(int)day{
    NSArray *array =[NSArray arrayWithObjects:@"周一",@"周二",@"周三",@"周四",@"周五",@"周六",@"周日", nil];
    return array[day-1];
}



- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [super scrollViewDidScroll:scrollView];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == self.tableView) {
        [super scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
    }
    
}

-(void)requestWeekVideoRule:(NSString *)class_id{
}


/*
 -(void)requestTodayWeekDay:(int)class_id{
 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
 
 NSString *request = [NSString stringWithFormat:@"{\"%@\":%d,\"%@\":%d}", JK_MESSAGE_TYPE,GET_CUR_VIDEO_TIME_RULE,JK_CLASS_ID,class_id];
 NSString *response;
 int tag =  [ZhongweiLib GetResponseByRequestShortConnectionServer:SCHOOL_INFO_PROCESS request:request response:&response];
 if (tag == 0) {
 
 NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
 
 NSError *error = nil;
 id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
 if (jsonObject) {
 currentDayUnit = [[WeekUnit alloc]init];
 
 currentDayUnit.week_day= [[jsonObject objectForKey:JK_WEEK_DAY] integerValue];
 
 currentDayUnit.week_rules = [jsonObject objectForKey:JK_WEEK_DAY_RULE];
 currentDayUnit.video_status =  [jsonObject objectForKey:JK_VIDEO_STATUS]==0;
 
 NSMutableString *str = [NSMutableString string];
 for (NSDictionary *dic in  currentDayUnit.week_rules) {
 if([currentDayUnit.week_rules indexOfObject:dic] != 0){
 [str appendString:@"\n"];
 }
 
 [str appendFormat:@"%@-%@", [dic objectForKey:JK_START_TIME], [dic objectForKey:JK_END_TIME]];
 }
 currentDayUnit.weekRulesStr = str;
 
 
 }
 }
 
 });
 }
 */

//当前本机时间与系统时间的时间差
-(NSTimeInterval)localTimeServerTimeInterval{
    
    if (!system_local_timeInterval) {
        
        NSDate *date = [NSDate date];
        NSTimeInterval time = [serverCurrentDate timeIntervalSinceDate:date];
        system_local_timeInterval = [NSNumber numberWithDouble:time];
        return time;
    }
    
    return [system_local_timeInterval doubleValue];
  }

/*
 -(BOOL)isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
 {
 NSDate *date = [NSDate date];
 
 if ([date compare:beginDate] == NSOrderedAscending)
 return NO;
 
 if ([date compare:endDate] == NSOrderedDescending)
 return NO;
 
 return YES;
 }*/



//-(void)getTodayWeekDay{
//    NSInteger week;
//
//    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
//    NSDate *now = [NSDate date];;
//    NSInteger unitFlags = NSWeekdayCalendarUnit;
//
//    NSDateComponents*comps = [calendar components:unitFlags fromDate:now];
//    week = [comps weekday];
//    //week 等于1 ，表示星期天
//    todayWeekDay=week-1;
//}

-(void)dealloc{
    [self removeBoardSideView];
}

//-(void)navLeftAction{
//    [self.navigationController trvs_popViewControllerWithNavigationControllerTransition];
//}

@end
